<template>
  <div :class="{'mobile-table': showMobilePage}" class="todo-card-container">
    <SwitchTab :active="activeId" :data="noticeTab" :font-size="fontSize" class="notice-tab" @switchTab="switchTab"/>
    <div v-loading="loading" :style="{ height: tableHeight + 'px' }" class="notice-table">
      <el-table
        v-el-table-infinite-scroll="loadMore"
        v-if="noticeData && noticeData.items && noticeData.items.length > 0"
        :data="noticeData ? noticeData.items : []"
        :show-header="false"
        :height="tableHeight"
        class="todo-table"
        @row-click="toDetail">
        <el-table-column min-width="80" align="left">
          <template slot-scope="scope">
            <div class="status-box">
              <p :class="`task-type type${[3, 5, 16, 17].includes(scope.row.type) ? scope.row.moduleType : scope.row.type}`">
                {{ getNotifyType(scope.row) }}
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column min-width="160">
          <template slot-scope="scope">
            <ToolTip :content="formatTitle(scope.row)" :style="{fontSize: showMobilePage ? '11px' : '14px'}" class="notice-title" />
          </template>
        </el-table-column>
        <el-table-column min-width="100">
          <template slot-scope="scope">
            <div class="color-status-box">
              <span v-if="activeId === 'notice' && !scope.row.read" class="dot"/>
              <img :src="scope.row.avatar || avatarPng" class="column-creator-img">
              <span class="user-name ellipsisOne">
                <ToolTip :content="scope.row.proposerName" :style="{fontSize: showMobilePage ? '12px' : '14px'}"/>
              </span>
            </div>
          </template>
        </el-table-column>
        <p v-if="noticeData.items.length > 6" slot="append" class="load-more">
          {{ !isMax ? '向下滚动加载更多↓' : '没有更多数据了~' }}
        </p>
      </el-table>
      <div v-if="noticeData.items.length === 0 && activeId === 'todo'" class="no-data no-todo-data">
        <img :src="noTodoImg" alt="no-todo-data">
        <p>暂无待办项，处理效率很高噢~</p>
      </div>
      <div v-if="noticeData.items.length === 0 && activeId === 'notice'" class="no-data no-notice-data">
        <img :src="noNoticeImg" alt="no-notice-data">
        <p>暂无通知消息~</p>
      </div>
    </div>
  </div>
</template>

<script>
import SwitchTab from '@/views/customer/module/switchTab';
import Todo from '@/mixins/todo';
import { globalNoticeField, globalNoticeRowField } from '@/views/todo/fieldData';
import { getList, getReceiveList, setListRead } from '@/api/todo';
import { taskType as notifyTypeToStr } from '@/filters/status';
import noTodoImg from '@/assets/empty-table-data.png';
import noNoticeImg from '@/assets/todo/noNotice.png';
import axios from 'axios';
import { mapState } from 'vuex';

export default {
  name: 'TodoCard',
  components: {
    SwitchTab
  },
  mixins: [Todo],
  props: {
    styleConfig: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      noTodoImg,
      noNoticeImg,
      globalNoticeField,
      globalNoticeRowField,
      activeId: 'todo',
      loading: false,
      noticeTab: [{
        name: '待办事项',
        class: 'todo',
        num: 0
      }, {
        name: '消息通知',
        class: 'notice',
        num: 0
      }],
      tableHeight: 200,
      noticeData: {
        items: []
      }
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    isMax() {
      return this.noticeData.items.length >= this.noticeData.total;
    },
    fontSize() {
      if (!this.styleConfig || !this.styleConfig.fontSize) {
        return '14px';
      } else {
        return `${this.styleConfig.fontSize}px`;
      }
    }
  },
  created() {
    this.getNoticeData();
    this.setTableHeight();
  },
  methods: {
    setTableHeight() {
      this.$nextTick(() => {
        const dom = document.querySelector('.todo-card-container');
        const containerHeight = dom && dom.clientHeight || 100;
        this.tableHeight = containerHeight - 40;
      });
    },
    resetTable: _.debounce(function() {
      this.setTableHeight();
    }, 800),
    switchTab(val) {
      this.activeId = val;
      this.noticeData.items = [];
      this.getNoticeData();
    },
    loadMore() {
      if (this.noticeData.items) {
        if (!this.isMax && !this.loading) {
          this.getNoticeData(this.noticeData.page + 1, true);
        }
      }
    },
    async setSingleRead(row) {
      if (this.activeId === 'notice' && !row.read) {
        await setListRead(row.id);
        const index = this.noticeData.items.findIndex(item => {
          return item.id === row.id;
        });
        if (index !== -1) {
          this.$set(this.noticeData.items[index], 'read', true);
        }
      }
    },
    async queryReceiveTab() {
      try {
        const params = {
          page: 1,
          perPage: 20,
          isExpedited: this.isExpedited,
          tabStatus: 0
        };
        const params1 = {
          page: 1,
          perPage: 20,
          tabStatus: 3,
          onlyUnread: 1
        };
        const res = await getList(params);
        const result = await getReceiveList(params1);
        this.noticeTab[0].num = res.data.total;
        this.noticeTab[1].num = result.data.total;
        this.$store.commit('SETNOTICENUM', { total: res.data.total, unTotal: result.data.total });
      } catch (error) {
        console.log(error);
      }
    },
    async getNoticeData(page = 1, concat = false) {
      this.loading = true;
      this.queryReceiveTab();
      const params = { page: page, perPage: 20 };
      let res = {};
      if (this.activeId === 'todo') {
        if (this.receiveListCancelToken) this.receiveListCancelToken.cancel('cancel');
        if (this.listCancelToken) this.listCancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.listCancelToken = source;
        params.tabStatus = 0;
        res = await getList(params, source.token);
      } else if (this.activeId === 'notice') {
        params.onlyUnread = 1;
        if (this.listCancelToken) this.listCancelToken.cancel('cancel');
        if (this.receiveListCancelToken) this.receiveListCancelToken.cancel('cancel');
        const source = axios.CancelToken.source();
        this.receiveListCancelToken = source;
        res = await getReceiveList(params, source.token);
        const data = res.data.items;
        if (data.length > 0) {
          res.data.items = data.map(item => {
            if (item.extendStr && this.isJSON(item.extendStr)) {
              const urlObj = JSON.parse(item.extendStr);
              item = { ...item, ...urlObj };
            }
            if (item.abstractStr && typeof item.abstractStr === 'string') {
              item.abstractStr = item.abstractStr.replace(/\n/g, '');
            }
            if (item.abstractStr && this.isJSON(item.abstractStr)) {
              const urlObj = JSON.parse(item.abstractStr);
              item = { ...item, ...urlObj };
            }
            return item;
          });
        }
      }
      if (res.data && res.data.items && res.data.items.length > 0) {
        res.data.items = concat ? this.noticeData.items.concat(res.data.items) : res.data.items;
      }
      this.noticeData = res.data || { items: [] };
      this.loading = false;
    },
    getNotifyType(data) {
      const { type, moduleType } = data || {};
      if (!type && type !== 0) return '--';
      const key = [3, 5, 16, 17].includes(type) ? moduleType : type;
      return notifyTypeToStr(key);
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/views/todo/todoTable.scss";
.todo-card-container {
  height: 100%;
  .todo-table {
    cursor: pointer;
  }
  .notice-tab {
    padding: 6px 0 0 12px;
    border-bottom: 1px solid #f5f5f5;
  }
  .notice-table {
    overflow-y: auto;
    .no-data {
      height: 100%;
      text-align: center;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      img {
        width: 100px;
        height: auto;
      }
      p {
        margin-top: 8px;
        font-size: 14px;
        color: #999;
      }
    }
    .status-box {
      display: flex;
      justify-content: center;
      .task-type {
        margin: 0;
        // width: auto;
        font-size: 10px;
        padding: 0 6px;
      }
    }
    .color-status-box {
      .user-name {
        white-space: nowrap;
      }
      .dot {
        left: 4px;
      }
    }
    & ::v-deep {
      .el-table {
        .el-table__row:hover {
          cursor: pointer !important;
        }
        .notice-title {
          font-size: 14px;
          color: #333;
          width: 100%;
        }
        .dot {
          left: 4px;
        }
        .load-more {
          display: flex;
          justify-content: center;
          margin: 0;
          padding: 4px 0;
          background-color: #F5F5F5;
          color: #999;
          font-weight: normal;
        }
        .column-creator-img {
          width: 24px;
          height: 24px;
          margin: 0 8px 0 12px;
          border-radius: 100%;
        }
        &::before {
          display: none;
        }
      }
    }
  }
}
.mobile-table {
  .notice-tab {
    padding-left: 0;
  }
  .notice-table {
    & ::v-deep {
      .el-table {
        .el-table__cell {
          height: 32px;
        }
      }
    }
  }
}
</style>
